package bb.lanxing.common.daemon;

import android.content.Context;
import android.os.Build;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class Command {
    public static final String BIN_DIR_NAME = "bin";
    private static final String TAG = "Command";

    private static void copyFile(File file, InputStream inputStream, String str) throws IOException, InterruptedException {
        String absolutePath = file.getAbsolutePath();
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        byte[] bArr = new byte[1024];
        while (true) {
            int read = inputStream.read(bArr);
            if (read > 0) {
                fileOutputStream.write(bArr, 0, read);
            } else {
                fileOutputStream.close();
                inputStream.close();
                Runtime runtime = Runtime.getRuntime();
                runtime.exec("chmod " + str + " " + absolutePath).waitFor();
                return;
            }
        }
    }

    public static void copyRawFile(Context context, int i, File file, String str) throws IOException, InterruptedException {
        copyFile(file, context.getResources().openRawResource(i), str);
    }

    public static void copyAssets(Context context, String str, File file, String str2) throws IOException, InterruptedException {
        copyFile(file, context.getAssets().open(str), str2);
    }

    public static boolean install(Context context, String str, String str2) {
        String str3 = Build.CPU_ABI;
        String str4 = TAG;
        Log.d(str4, "abi = " + str3);
        if (!str3.startsWith("arm")) {
            return false;
        }
        try {
            copyAssets(context, str2, new File(context.getDir(str, 0), str2), "0755");
            return true;
        } catch (Exception e) {
            String str5 = TAG;
            Log.e(str5, "installBinary failed: " + e);
            return false;
        }
    }

    public static void install(Context context, String str) {
        install(context, BIN_DIR_NAME, str);
    }
}
